package com.securityLearn.securityAuth.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
public class LoginController {

    /**
     * 登录页
     *
     * @return
     */
    @RequestMapping("/")
    public String toLogin() {
        // 跳转至 Security 提供的登录页面
        return "redirect:/login";
    }

    /**
     * 登录页（自定义页面）
     *
     * @return
     */
    @RequestMapping("/myLogin")
    public String myLogin() {
        return "login";
    }

    /**
     * 登录页（自定义页面）
     *
     * @return
     */
    @RequestMapping("/myLoginSubmit")
    public String myLoginSubmit() {
        return "login";
    }

    /**
     * 登录成功后，跳转的页面
     * @return
     */
    @ResponseBody
    @RequestMapping("/login-success")
    public Object loginSuccess() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!authentication.isAuthenticated()){
            return null;
        }
        Object principal = authentication.getPrincipal();
        return principal;
    }

    /**
     * 测试资源1
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=UTF-8"})
    public String r1() {
        return " 访问资源1";
    }

    /**
     * 测试资源2
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=UTF-8"})
    public String r2() {
        return " 访问资源2";
    }
}
